import MaskText from '@/components/MaskText';
import { fenceUserTypeHash } from '.';
import Ellipsis from '../../../components/Ellipsis';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import WarningConfigModal from './warningConfigModal';
import { filterAuth } from '@/support/common';
import { downloadFileByUrl } from '@/utils/utils';
import { ExportOutlined, PlusOutlined, ImportOutlined, UploadOutlined } from '@ant-design/icons';
import { Card, Button, message, Descriptions, Modal, Upload } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import * as XLSX from 'xlsx';

const mapStateToProps = (state: any) => ({
  electricFenceMng: state.electricFenceMng,
  loading: state.loading.effects['electricFenceMng/getFetchPage'],
});
class CustomizeFence extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      exportLoading: false,
      formValues: { fenceType: 0 },
      dealerData: [],
      uploadVisible: false,
      templateFileUrl: null,
      imports: [],
      importLoading: false,
      saveLoading: false,
      importSuccessNum: 0,
      importFailNum: 0,
      importResultExcelUrl: '',
      importResultModalShow: false,
      workbook: null,
      errorImports: [],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/getFetchPage',
      payload: { url: '/electricfence/findfencebypage', fenceType: 0 },
    });
    // this.initDealerData();
    dispatch({
      type: 'electricFenceMng/getData',
      payload: { url: '/common/template/detail', templateCode: 'customizeFenceImport' },
      callback: (res: any) => {
        this.setState({ templateFileUrl: res.data ? res.data.templateUrl : null });
      },
    });
    dispatch({
      type: 'basedata/fetchDealerByLogin',
      callback: (response: { data: { name: any; code: any }[] }) => {
        //  需求迭代20231211：显示内容为“经销商名称(经销商编码)”
        const dealerData = response?.data?.map((o: { name: any; code: any }) => {
          return {
            label: `${o.name}(${o.code})`,
            value: o.code,
          };
        });
        this.setState({
          dealerData: dealerData || [],
        });
      },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/initData',
    });
  }

  // initDealerData = () => {
  //   this.setState({ dealerData: [] });

  //   const dealTreeData = (
  //     orgParent: any,
  //     list: {
  //       map: (arg0: (e: any) => { orgParent: any; sid: any; value: any; label: any }) => {
  //         (): any;
  //         new (): any;
  //         filter: { (arg0: (c: any) => boolean): never[]; new (): any };
  //       };
  //     },
  //   ) => {
  //     const arr =
  //       list
  //         .map((e: { orgParent: any; sid: any; orgCode: any; orgName: any }) => ({
  //           orgParent: e.orgParent,
  //           sid: e.sid,
  //           value: e.orgCode,
  //           label: e.orgName,
  //         }))
  //         .filter((c: { orgParent: any }) => c.orgParent === orgParent) || [];
  //     arr.forEach((item: { sid: any; children: any }) => {
  //       const children = dealTreeData(item.sid, list);
  //       if (children.length) {
  //         item.children = children;
  //       }
  //     });
  //     return arr;
  //   };

  //   this.props.dispatch({
  //     type: 'http/getData',
  //     payload: {
  //       url: '/org/findorglistbytoken',
  //     },
  //     // callback: res => {
  //     //   if (res.statusCode === '0' && res.data && res.data.length) {
  //     //     const orgData = res.data;
  //     //     const current = orgData[0];
  //     //     if (current.orgType === 3) {
  //     //       // todo: 如果是授信机构, 是另外的逻辑, 待实现
  //     //       return;
  //     //     } else {
  //     //       this.setState({
  //     //         dealerData: [
  //     //           {
  //     //             label: current.orgName,
  //     //             value: current.orgCode,
  //     //             children: dealTreeData(
  //     //               current.sid,
  //     //               orgData.filter(e => [1, 2].indexOf(e.orgType) >= 0),
  //     //             ),
  //     //           },
  //     //         ],
  //     //       });
  //     //     }
  //     //   }
  //     // },
  //     callback: (res: any) => {
  //       if (res.statusCode === '0' && res.data && res.data.length) {
  //         let orgData = res.data;
  //         const current = orgData[0];
  //         orgData = orgData.filter((item: any) => item.orgType === 2);
  //         if (current.orgType === 3) {
  //           // todo: 如果是授信机构, 是另外的逻辑, 待实现
  //           return;
  //         } else {
  //           this.setState({
  //             dealerData: dealTreeData(current.sid, orgData),
  //           });
  //         }
  //       }
  //     },
  //   });
  // };

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'electricFenceMng/getFetchPage',
      payload: { url: '/electricfence/findfencebypage', ...formValues },
    });
  };

  handleRemove = (id: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/delData',
      payload: {
        url: '/electricfence/deletefence?fenceId=' + id,
      },
      callback: (res: any) => {
        message.success('删除成功');
        this.handleFlushPage();
      },
    });
  };

  // 关联授信车辆
  handleRelative = ({ fenceId, dealerCode, orgId }) => {
    sessionStorage.setItem('dealerCode', dealerCode);
    sessionStorage.setItem('fenceId', fenceId);
    sessionStorage.setItem('fenceOrgId', orgId);
    router.push({
      pathname: '/electricFence/electricFenceMng/relateVehicle',
      query: { fenceId },
    });
  };
  onRef = (ref: any) => {
    this.warningConfigModalRef = ref;
  };

  // 设置预警方式
  setWarningConfig = (record: any) => {
    this.warningConfigModalRef.showModal(record);
  };
  handleAdd = () => {
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/customizeAdd`,
    });
  };

  handleEdit = (record: any) => {
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/customizeAdd`,
      query: { fenceId: record.fenceId },
    });
  };

  handleDetail = (record: any) => {
    // router.push({
    //   pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/detailAndExport`,
    //   query: { fenceId: record.fenceId },
    // });
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/customizeAdd`,
      query: { fenceId: record.fenceId, isDetail: true },
    });
  };

  handleExport = () => {
    const { dispatch } = this.props;
    this.setState({ exportLoading: true });
    dispatch({
      type: 'http/postObj',
      payload: {
        url: '/electricfence/exportfence',
        fenceName: this.state.formValues.fenceName,
        dealerCode: this.state.formValues.dealerCode,
        fenceUserType: this.state.formValues.fenceUserType,
        fenceType: 0,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const data: {
            index: any;
            fenceCode: any;
            fenceName: any;
            fenceUserType: any;
            orgName: any;
            dealer: any;
            // warningConfigDesc: any;
            fenceCenterDesc: any;
            fenceCenterPoint: any;
            fenceExpireDate: string;
            createBy: any;
            createDate: string;
          }[] = [];
          res.data.forEach(
            (
              e: {
                fenceCode: any;
                fenceName: any;
                fenceUserType: any;
                orgName: any;
                dealerName: any;
                dealerCode: any;
                // warningConfigDesc: any;
                fenceCenterDesc: any;
                fenceCenterPoint: any;
                warningBeginDate: moment.MomentInput;
                warningEndDate: moment.MomentInput;
                createBy: any;
                createDate: moment.MomentInput;
              },
              i: number,
            ) => {
              const dealerName = e.dealerName ?? '';
              const dealerCode = e.dealerCode ?? '';
              data.push({
                index: i + 1,
                fenceCode: e.fenceCode,
                fenceName: e.fenceName,
                fenceUserType: fenceUserTypeHash[e.fenceUserType],
                orgName: e.orgName,
                dealer: dealerName + (dealerCode ? '(' + dealerCode + ')' : ''),
                // warningConfigDesc: e.warningConfigDesc,
                fenceCenterDesc: e.fenceCenterDesc,
                fenceCenterPoint: e.fenceCenterPoint,
                fenceExpireDate:
                  e.warningBeginDate && e.warningEndDate
                    ? `${moment(e.warningBeginDate).format('YYYY-MM-DD')} ~ ${moment(
                        e.warningEndDate,
                      ).format('YYYY-MM-DD')}`
                    : '无限制',
                createBy: e.createBy,
                createDate: e.createDate ? moment(e.createDate).format('YYYY-MM-DD') : '',
              });
            },
          );
          const header = {
            index: '序号',
            fenceCode: '围栏编号',
            fenceName: '围栏名称',
            fenceUserType: '围栏类型',
            orgName: '所属组织',
            dealer: '所属经销商',
            // warningConfigDesc: '预警方式',
            fenceCenterDesc: '围栏中心点位置',
            fenceCenterPoint: '围栏中心点经纬度',
            fenceExpireDate: '围栏有效期',
            createBy: '创建人',
            createDate: '创建时间',
          };
          const ws = XLSX.utils.json_to_sheet([header, ...data], { skipHeader: true });
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'export');
          const fileName = `自定义电子围栏${moment().format('YYYYMMDDHHmmss')}.xlsx`;
          XLSX.writeFile(wb, fileName);
        } else {
          message.error('导出失败');
        }
      },
    }).finally(() => this.setState({ exportLoading: false }));
  };
  beforeFileUpload = async (file: any) => {
    if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      message.warning('请上传xlsx格式文件');
      return false;
    }
    if (file.size / 1024 / 1024 > 10) {
      message.warning('文件大小不能大于10MB');
      return false;
    }

    this.setState({ importLoading: true });
    let errorImports: number[] = [];
    const self = this;
    const imports = await new Promise(resolve => {
      const reader = new FileReader();
      reader.onload = function (e: any) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array', cellDates: true });
        self.setState({ workbook: workbook });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        let res = XLSX.utils.sheet_to_json(worksheet, { header: 1 }).slice(1);
        // 1-围栏类型 1-组织, 2-经销商, 3-所属仓库, 4-开始时间, 5-结束时间 6-纬度 7-经度 8- 半径 9-中心点地址
        res = res || [];
        const imports = [];
        for (let i = 0; i < res.length; i++) {
          let e = res[i];
          e = e || [];
          if (!e.join('')) {
            // 过滤全部为空行的情况
            continue;
          }
          const fenceUserType = e[0];
          const orgName = e[1];
          const dealerName = e[2];
          const repository = e[3];
          // 日期行如果有数据且不为日期格式
          if ((!!e[4] && !(e[4] instanceof Date)) || (!!e[5] && !(e[5] instanceof Date))) {
            message.error('导入文件参数异常，请检查！');
            return;
          }
          // excel转出的iso 8061时间差43s，+1h补齐到当日
          const warningBeginDate = !!e[4] ? moment(e[4]).add(1, 'h').format('YYYY-MM-DD') : '';
          const warningEndDate = !!e[5] ? moment(e[5]).add(1, 'h').format('YYYY-MM-DD') : '';
          const centerLat = e[6];
          const centerLng = e[7];
          const radius = e[8];
          const fenceCenterAddress = e[9];
          let isError = false;
          let errorStrArr = [];
          if (!centerLng) {
            isError = true;
            errorStrArr.push('经度不能为空');
          }
          if (parseFloat(centerLng) < -180 || parseFloat(centerLng) > 180) {
            isError = true;
            errorStrArr.push('经度为不合理值');
          }
          if (!centerLat) {
            isError = true;
            errorStrArr.push('纬度不能为空');
          }
          if (parseFloat(centerLat) < -90 || parseFloat(centerLat) > 90) {
            isError = true;
            errorStrArr.push('纬度为不合理值');
          }
          if (!radius) {
            isError = true;
            errorStrArr.push('半径不能为空');
          }
          if (parseFloat(radius) < 0) {
            isError = true;
            errorStrArr.push('半径不能为负数');
          }
          // imports.map(e => {
          //   if (e.centerLng === centerLng && e.centerLat === centerLat && e.radius === radius) {
          //     isError = true;
          //     errorStrArr.push('重复数据');
          //   }
          // });
          if (isError) {
            let errorStr = errorStrArr.join('、');
            XLSX.utils.sheet_add_aoa(worksheet, [[errorStr]], { origin: `D${i + 2}` });
            errorImports.push(i);
          } else {
            imports.push({
              fenceUserType,
              orgName,
              dealerName,
              repository,
              warningBeginDate,
              warningEndDate,
              centerLat,
              centerLng,
              radius,
              fenceCenterAddress,
            });
          }
        }
        resolve(imports);
      };
      reader.readAsArrayBuffer(file);
    })
      .catch(e => {
        console.log(e);
      })
      .finally(() => {
        this.setState({ importLoading: false });
      });

    this.setState({ imports: imports || [] });
    this.setState({ errorImports: errorImports || [] });
    return false;
  };

  handleImport = async () => {
    const { dispatch } = this.props;
    this.setState({ saveLoading: true });
    const result = await dispatch({
      type: 'http/postListList',
      payload: {
        url: '/commodity/vehicle/fences/import',
        list: this.state.imports,
      },
    });
    await this.setState({
      uploadVisible: false,
      imports: [],
      saveLoading: false,
      importSuccessNum: result?.data?.successNum || 0,
      importFailNum: result?.data ? result?.data?.failNum : '文件导入失败',
      importResultExcelUrl: result?.data?.resulExceltUrl,
      importResultModalShow: true,
      errorImports: [],
    });
    this.handleFlushPage();
  };
  render() {
    const {
      electricFenceMng: {
        pageData: { list, pagination },
      },
      loading,
      pathname,
      permissions,
    } = this.props;
    const { formValues, dealerData, templateFileUrl, importResultModalShow, uploadVisible } =
      this.state;
    const columns = [
      {
        title: '围栏编号',
        dataIndex: 'fenceCode',
      },
      {
        title: '围栏名称',
        dataIndex: 'fenceName',
      },
      {
        title: '围栏类型',
        dataIndex: 'fenceUserType',
        render: (text: any) => fenceUserTypeHash[text + ''],
      },
      {
        title: '所属组织',
        dataIndex: 'orgName',
      },
      {
        title: '所属经销商',
        dataIndex: 'dealer',
        render: (text: any, record: any) => {
          const dealerName = record.dealerName ?? '';
          const dealerCode = record.dealerCode ?? '';

          return (
            <Ellipsis length={20} tooltip>
              {dealerName + (dealerCode ? '(' + dealerCode + ')' : '')}
            </Ellipsis>
          );
        },
      },
      // {
      //   title: '预警方式',
      //   dataIndex: 'warningConfigDesc',
      // },
      {
        title: '围栏中心点位置',
        dataIndex: 'fenceCenterDesc',
        render: (text: any) => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '围栏中心点经纬度',
        dataIndex: 'fenceCenterPoint',
      },
      {
        title: '围栏有效期',
        render: (text: any) => {
          return text.warningBeginDate && text.warningEndDate
            ? `${moment(text.warningBeginDate).format('YYYY-MM-DD')} ~ ${moment(
                text.warningEndDate,
              ).format('YYYY-MM-DD')}`
            : '无限制';
        },
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text: any) => {
          return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null;
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 218,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看',
              key: 'detail',
              auth: 'electricFenceMng_doDetail',
              onConfirm: () => this.handleDetail(record),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'electricFenceMng_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'electricFenceMng_doDel',
              Popconfirm: true,
              message: '是否确认删除？',
              onConfirm: () => this.handleRemove(record.fenceId),
            },
            {
              title: '设置预警方式',
              key: 'settingWarning',
              auth: 'electricFenceMng_doSettingWarningConfig',
              onConfirm: () => this.setWarningConfig(record),
            },
          ];
          const relativeBtn = {
            title: '关联授信车辆',
            key: 'relative',
            auth: 'electricFenceMng_doRelateVehicle',
            onConfirm: () => this.handleRelative(record),
          };
          if (record.fenceUserType === '1') btns.push(relativeBtn);
          return <PateoAuthButtons btns={btns} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.fenceId,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '围栏名称',
        key: 'fenceName',
      },
      {
        type: 'select',
        title: '围栏类型',
        key: 'fenceUserType',
        selectOptions: [
          { value: '0', label: '非经销商' },
          { value: '1', label: '经销商' },
        ],
      },
      {
        type: 'select',
        title: '所属经销商',
        key: 'dealerCode',
        selectOptions: dealerData,
        // keyValue: ['code', 'name'], // name一会儿改shortName 一会儿又要改回来 都是你们说的 还不把信息同步前端 后台你们牛x好吧
        keyValue: ['value', 'label'], //  取处理后的options的value和label
      },
      // {
      //   type: 'cascader',
      //   title: '经销商',
      //   key: 'dealerCode',
      //   selectOptions: this.state.dealerData,
      //   separator: '/',
      //   changeOnSelect: true,
      // },
    ];
    let isAdd = filterAuth('electricFenceMng_doAdd', permissions, pathname);
    let isExport = filterAuth('electricFenceMng_doExport', permissions, pathname);
    let isBatchImport = filterAuth('electricFenceMng_doBatchImport', permissions, pathname);
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'electricFenceMng/getFetchPage',
              url: '/electricfence/findfencebypage',
            }}
            extraArgs={{ fenceType: 0 }}
            saveFormValues={(val: any) => {
              return this.setState({ formValues: Object.assign(formValues, val) });
            }}
            handleFormReset={() => this.setState({ formValues: { fenceType: 0 } })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {isAdd || isExport || isBatchImport ? (
            <div className="my_newItem">
              {isAdd ? (
                <Button
                  size="small"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => this.handleAdd()}
                >
                  新增
                </Button>
              ) : null}
              {isBatchImport ? (
                <Button
                  size="small"
                  icon={<ImportOutlined />}
                  type="primary"
                  onClick={() => this.setState({ uploadVisible: true })}
                >
                  批量导入
                </Button>
              ) : null}
              {isExport ? (
                <Button
                  size="small"
                  icon={<ExportOutlined />}
                  type="primary"
                  onClick={() => this.handleExport()}
                  loading={this.state.exportLoading}
                >
                  导出
                </Button>
              ) : null}
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'electricFenceMng/getFetchPage',
              url: '/electricfence/findfencebypage',
            }}
            formValues={formValues}
          />
          <Modal
            title="批量导入"
            visible={uploadVisible}
            okButtonProps={{ size: 'small' }}
            cancelButtonProps={{ size: 'small' }}
            onCancel={() => this.setState({ uploadVisible: false, imports: [], errorImports: [] })}
            footer={[
              <Button
                loading={this.state.saveLoading}
                key="back"
                type="primary"
                size="small"
                onClick={this.handleImport}
              >
                保存
              </Button>,
            ]}
          >
            <Descriptions column={1} style={{ paddingTop: 10, paddingLeft: 8 }}>
              <Descriptions.Item label="模板">
                {templateFileUrl ? (
                  <a
                    onClick={() => {
                      downloadFileByUrl(
                        templateFileUrl,
                        `批量导入自定义电子围栏${moment().format('YYYYMMDD')}.xlsx`,
                      );
                    }}
                  >
                    下载模板文件
                  </a>
                ) : (
                  '暂无模板文件'
                )}
              </Descriptions.Item>
              <Descriptions.Item label="文件" style={{ position: 'relative' }}>
                <Upload
                  className={styles.uploadFile}
                  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  // onChange={this.handleFileChange}
                  // showUploadList={true}
                  beforeUpload={this.beforeFileUpload}
                  loading={this.state.importLoading}
                  maxCount={1}
                  onChange={e => {
                    if (e.file.status === 'removed') {
                      this.setState({
                        imports: [],
                        errorImports: [],
                      });
                    }
                  }}
                >
                  <Button size="small" icon={<UploadOutlined />} type="primary">
                    导入
                  </Button>
                </Upload>
                <div style={{ position: 'absolute', top: 2, left: 125 }}>
                  成功导入{this.state.imports.length}条
                  {this.state.errorImports.length > 0
                    ? `    失败导入${this.state.errorImports.length}条`
                    : ''}
                </div>
              </Descriptions.Item>
            </Descriptions>
          </Modal>
          <Modal
            title="上传结果"
            visible={importResultModalShow}
            footer={null}
            onCancel={() => this.setState({ importResultModalShow: false })}
          >
            <p>上传成功：{this.state.importSuccessNum}</p>
            <p>上传失败：{this.state.importFailNum}</p>
            {this.state.importResultExcelUrl ? (
              <a href={this.state.importResultExcelUrl} title="点击下载结果文件">
                下载结果文件
              </a>
            ) : null}
          </Modal>
        </Card>
        <WarningConfigModal
          onRef={this.onRef}
          icon="plus"
          type="primary"
          dispatch={this.props.dispatch}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(CustomizeFence);
